package gw.com.android.ui.chart.views;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.MainActivity;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.AppActivities;
import www.com.library.app.ObjectSessionStore;
import www.com.library.model.DataItemResult;
import www.com.library.util.DoubleConverter;

/**
 * Created by hubble on 2017/3/8.
 */

public class PositionInQuoteViewHolder {

    private ListView mLvExpandable;
    private PositionInQuoteAdapter mAdapter;
    private RelativeLayout mRlCollapsed;
    private TextView mCollapsedText;
    private ImageView mIvSwitch;
    private TextView mTvBuyLots;
    private TextView mTvSellLots;
    private TextView mTvBuyProfits;
    private TextView mTvSellProfits;
    private TextView mTvTotalProfits;
    private TextView mTvTotalProfitsBottom;
    private int mCodeId;
    private int mMinHeight;
    private int mMaxHeight;
    private final View headView;
    private View divider1;
    private View divider2;
    private View divider3;
    private View topDivider;
    private TextView footText;

    private final Context context;

    public PositionInQuoteViewHolder(final Activity context, View view, int codeId) {
        this.context = context;
        mCodeId = codeId;
        mLvExpandable = (ListView) view.findViewById(R.id.lv_expandable);
        topDivider = view.findViewById(R.id.top_divide);
        headView = context.getLayoutInflater().inflate(R.layout.view_position_in_chart_head, null);
        headView.setClickable(false);
        headView.setEnabled(false);
        mTvBuyLots = (TextView) headView.findViewById(R.id.tv_buy_lot);
        mTvSellLots = (TextView) headView.findViewById(R.id.tv_sell_lot);
        mTvBuyProfits = (TextView) headView.findViewById(R.id.tv_buy_profit);
        mTvSellProfits = (TextView) headView.findViewById(R.id.tv_sell_profit);
        mTvTotalProfits = (TextView) headView.findViewById(R.id.tv_total_profit);
        mTvTotalProfitsBottom = (TextView) view.findViewById(R.id.tv_total_profit_bottom);
        divider1 = headView.findViewById(R.id.divider1);
        divider2 = headView.findViewById(R.id.divider2);
        divider3 = headView.findViewById(R.id.divider3);
        View foot = context.getLayoutInflater().inflate(R.layout.view_position_in_chart_footer, null);
        footText = (TextView) foot.findViewById(R.id.chart_quote_foot_text);
        mLvExpandable.addHeaderView(headView);
        mLvExpandable.addFooterView(foot);
        mAdapter = new PositionInQuoteAdapter(context, mLvExpandable);
        mLvExpandable.setAdapter(mAdapter);
        mRlCollapsed = (RelativeLayout) view.findViewById(R.id.rl_collapsed);
        mCollapsedText = (TextView) view.findViewById(R.id.tv_collapsed_text);
        mIvSwitch = (ImageView) view.findViewById(R.id.iv_switch);
        //mIvSwitch.setPivotX();
        mMinHeight = (int) context.getResources().getDimension(R.dimen.height_c);
        mMaxHeight = (int) context.getResources().getDimension(R.dimen.height_k_new);


        foot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppActivities.getSingleton().popAllActivityExceptOne(MainActivity.class.getSimpleName());
                MainActivity mainActivity = (MainActivity) ObjectSessionStore.getObject(MainActivity.class.getSimpleName() + GTSDataListener.mainNum);
                if (null != mainActivity) {
                    mainActivity.setTabFragment(ConfigType.TAB_TRADE_TAG, ConfigType.TAB_POSITION_TYPE);
                }
                context.finish();
            }
        });
        mIvSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mLvExpandable.isShown()) {
                    expandView(mLvExpandable, mMinHeight, mMaxHeight);
                    //mIvSwitch.setImageResource(R.mipmap.a_popup_down);
                } else {
                    collpaseView(mLvExpandable, mMaxHeight, mMinHeight);
                    //mIvSwitch.setImageResource(R.mipmap.a_popup_up);
                }
            }
        });
    }

    public void onNightMode(boolean isNight) {
        if (isNight) {
            mRlCollapsed.setBackgroundColor(context.getResources().getColor(R.color.color_night_bg));
            mCollapsedText.setTextColor(context.getResources().getColor(R.color.color_night_text));
            mLvExpandable.setBackgroundColor(context.getResources().getColor(R.color.color_night_bg));
            headView.setBackgroundColor(context.getResources().getColor(R.color.color_night_bg));
            divider1.setBackgroundColor(context.getResources().getColor(R.color.color_night_line));
            divider2.setBackgroundColor(context.getResources().getColor(R.color.color_night_line));
            divider3.setBackgroundColor(context.getResources().getColor(R.color.color_night_line));
            topDivider.setBackgroundColor(context.getResources().getColor(R.color.color_night_line));
            footText.setTextColor(context.getResources().getColor(R.color.color_night_text));
            mIvSwitch.setImageResource(R.mipmap.a_popup_night_down);
        } else {
            mRlCollapsed.setBackgroundColor(context.getResources().getColor(R.color.color_charttab_a));
            mCollapsedText.setTextColor(context.getResources().getColor(R.color.color_b));
            mLvExpandable.setBackgroundColor(context.getResources().getColor(R.color.color_charttab_a));
            headView.setBackgroundColor(context.getResources().getColor(R.color.color_charttab_a));
            divider1.setBackgroundColor(context.getResources().getColor(R.color.color_d));
            divider2.setBackgroundColor(context.getResources().getColor(R.color.color_d));
            divider3.setBackgroundColor(context.getResources().getColor(R.color.color_d));
            topDivider.setBackgroundColor(context.getResources().getColor(R.color.color_d));
            footText.setTextColor(context.getResources().getColor(R.color.color_b));
            mIvSwitch.setImageResource(R.mipmap.a_popup_down);
        }
        if (mAdapter != null) {
            mAdapter.onNightMode(isNight);
        }
    }

    /**
     * 还原设置状态
     */
    public void resetView(boolean isNight) {
        collpaseView(mLvExpandable, mMaxHeight, mMinHeight);
        mIvSwitch.setImageResource(isNight ? R.mipmap.a_popup_night_down : R.mipmap.a_popup_down);
    }

    public boolean refreshData(boolean isUpate) {
        DataItemResult positions = DataManager.instance().getPositionByCodeId(mCodeId);
        if (positions.getDataCount() < 1) {
            return false;
        }
        if (isUpate) {
            mAdapter.notifyDataSetChanged();
        } else {
            mAdapter.updateData(positions);
        }
        // 总盈亏
        double totalProfit = DoubleConverter.toDoubleData(positions.detailInfo.getString(GTSConst.JSON_KEY_POSITION_TOTAL_PROFITS));
        // 总买手
        double totalBuyLots = DoubleConverter.toDoubleData(positions.detailInfo.getString(GTSConst.JSON_KEY_POSITION_TOTAL_BUY_LOTS));
        // 总买入盈利
        double totalBuyProfit = DoubleConverter.toDoubleData(positions.detailInfo.getString(GTSConst.JSON_KEY_POSITION_TOTAL_BUY_PROFITS));
        // 总卖手
        double totalSellLots = DoubleConverter.toDoubleData(positions.detailInfo.getString(GTSConst.JSON_KEY_POSITION_TOTAL_SELL_LOTS));
        // 总卖出盈利
        double totalSellProfit = DoubleConverter.toDoubleData(positions.detailInfo.getString(GTSConst.JSON_KEY_POSITION_TOTAL_SELL_PROFITS));


        mTvTotalProfits.setText(DoubleConverter.toStringData(totalProfit, 2));
        mTvTotalProfitsBottom.setText(DoubleConverter.toStringData(totalProfit, 2));
        int direction = totalProfit > 0 ? AppContances.PRICE_INCREASE : (totalProfit < 0 ? AppContances.PRICE_DECREASE : AppContances.PRICE_UNCHANGE);
        ColorThemeUtil.instance().setPriceColor(mTvTotalProfits, direction);
        ColorThemeUtil.instance().setPriceColor(mTvTotalProfitsBottom, direction);

        mTvBuyLots.setText(AppMain.getAppString(R.string.quote_position_buy_lots, DoubleConverter.toStringData(totalBuyLots, 2)));
        mTvSellLots.setText(AppMain.getAppString(R.string.quote_position_sell_lots, DoubleConverter.toStringData(totalSellLots, 2)));

        mTvBuyProfits.setText(DoubleConverter.toStringData(totalBuyProfit, 2));
        direction = totalBuyProfit > 0 ? AppContances.PRICE_INCREASE : (totalBuyProfit < 0 ? AppContances.PRICE_DECREASE : AppContances.PRICE_UNCHANGE);
        ColorThemeUtil.instance().setPriceColor(mTvBuyProfits, direction);

        mTvSellProfits.setText(DoubleConverter.toStringData(totalSellProfit, 2));
        direction = totalSellProfit > 0 ? AppContances.PRICE_INCREASE : (totalSellProfit < 0 ? AppContances.PRICE_DECREASE : AppContances.PRICE_UNCHANGE);
        ColorThemeUtil.instance().setPriceColor(mTvSellProfits, direction);

        return true;
    }

    private void expandView(final View view, final int fromHeight, final int toHeight) {
        ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
        animator.setDuration(400);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                view.setVisibility(View.VISIBLE);
                mRlCollapsed.setVisibility(View.GONE);
                mIvSwitch.setClickable(false);

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mIvSwitch.setClickable(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Float value = (float) animation.getAnimatedValue();
                ViewGroup.LayoutParams lp = view.getLayoutParams();
                lp.height = fromHeight + (int) (value * (toHeight - fromHeight));

                view.setLayoutParams(lp);
                view.requestLayout();

                mIvSwitch.setRotation(value * 180);
            }
        });
        animator.start();
    }

    private void collpaseView(final View view, final int fromHeight, final int toHeight) {
        ValueAnimator animator = ValueAnimator.ofFloat(1, 0);
        animator.setInterpolator(new AccelerateInterpolator());
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                mIvSwitch.setClickable(false);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mLvExpandable.setVisibility(View.INVISIBLE);
                mRlCollapsed.setVisibility(View.VISIBLE);
                mIvSwitch.setClickable(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Float value = (float) animation.getAnimatedValue();
                ViewGroup.LayoutParams lp = view.getLayoutParams();
                lp.height = toHeight + (int) (value * (fromHeight - toHeight));

                view.setLayoutParams(lp);
                view.requestLayout();
                mIvSwitch.setRotation(value * 180);
            }
        });
        animator.start();
    }

}
